#!/usr/bin/python
# -*- coding: utf-8 -*-
#/*
# *      Copyright (C) 2012 by Tolin
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# */

import urllib2, re, httplib, xbmc, xbmcgui, xbmcplugin, cookielib, xbmcaddon, os, urllib, urllib2, socket

icon = xbmc.translatePath(os.path.join(os.getcwd().replace(';', ''), 'icon.png'))
siteUrl = 'www.filmy.net.ua'
httpSiteUrl = 'http://' + siteUrl

h = int(sys.argv[1])


def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

def showMessage(heading, message, times = 5000):
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))
	
#def GET(url):
#	try:
#		print 'def GET(%s):'%url
#		req = urllib2.Request(url)
#		f = urllib2.urlopen(req)
#		a = f.read()
#		f.close()
#		return a
#	except:
#		showMessage('Не могу открыть URL def GET', url)
#		return None

headers  = {
		'User-Agent' : 'Opera/9.80 (X11; Linux i686; U; ru) Presto/2.7.62 Version/11.00',
		'Accept'     :' text/html, application/xml, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*',
		'Accept-Language':'ru-RU,ru;q=0.9,en;q=0.8',
		'Accept-Charset' :'utf-8, utf-16, *;q=0.1',
		'Accept-Encoding':'identity, *;q=0'
	}

sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'plugin_video_filmy.sid')


def GET1(target, referer, post_params = None):
	try:
		connection = httplib.HTTPConnection(siteUrl)

		if post_params == None:
			method = 'GET'
			post = None
		else:
			method = 'POST'
			post = urllib.urlencode(post_params)
			headers['Content-Type'] = 'application/x-www-form-urlencoded'

		if os.path.isfile(sid_file):
			fh = open(sid_file, 'r')
			csid = fh.read()
			fh.close()
			headers['Cookie'] = 'sid=%s' % csid

		headers['Referer'] = referer
		connection.request(method, target, post, headers = headers)
		response = connection.getresponse()

		try:
				sc = Cookie.SimpleCookie()
				sc.load(response.msg.getheader('Set-Cookie'))
				fh = open(sid_file, 'w')
				fh.write(sc['sid'].value)
				fh.close()
		except: pass

		http = response.read()
#		http = http.decode('koi8-r').encode('utf-8')

		return http
	except Exception, e:
		showMessage(target, e, 5000)
		return None


def GET(url):
	try:
		print 'def GET(%s):'%url
		req = urllib2.Request(url)
		f = urllib2.urlopen(req)
		a = f.read()
		f.close()
		return a
	except:
		showMessage('Не могу открыть URL def GET', url)
		return None

	

def ROOT():


	http = GET(httpSiteUrl + '/film/')
	if http == None: return False

	
	r1 = re.compile('<div id="menubar">(.*?)<td valign="top">',re.S).findall(http)
	r2 = re.compile('<a href="(.*?)" title="(.*?)">.*?</a>').findall(r1[0])
	r3 = re.compile('</font>(.*?)<font color="Black">').findall(r1[0])
	
	href = httpSiteUrl + '/rating/'
	li = xbmcgui.ListItem("Топ скачиваний", iconImage = icon, thumbnailImage = icon)
	uri = sys.argv[0] + '?mode=OPEN_MOVIES1'
	uri += '&url='+urllib.quote_plus(href)
	xbmcplugin.addDirectoryItem(h, uri, li, True)

	href = httpSiteUrl + '/last/'
	li = xbmcgui.ListItem("Последние поступления", iconImage = icon, thumbnailImage = icon)
	uri = sys.argv[0] + '?mode=OPEN_MOVIES1'
	uri += '&url='+urllib.quote_plus(href)
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	
	rr=1
	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов name,link')
		return False
	for href, name in r2:
		img=icon
		
#		showMessage('r3', urllib.quote_plus(httpSiteUrl + href))
		name = '[COLOR ffDAA520]%s[/COLOR]' % (name)
		rr3 = '[COLOR ffDAA520]%s[/COLOR]' % r3[rr]
		name = name + '         ' + '[' + rr3 + ']'
		i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
#		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=OPEN_MOVIES'
		u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
		rr = rr + 1
		xbmcplugin.addDirectoryItem(h, u, i, True)
		
	xbmcplugin.endOfDirectory(h)





	
def PLAY3(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('img', urllib.unquote_plus(params['img']))
	if http == None: return False
#	img1 = re.compile('<div id="media_left">(.*?)<div id="media_right">',re.S).findall(http)
#	img = re.compile('<img src="(.*?)" border').findall(img1[0])
	img = urllib.unquote_plus(params['img'])
#	img = icon
	
#	rows = re.compile('<!-- -->(.*?)<script',re.S).findall(http)
#	rows1 = re.compile('<td class="file_2"><a href="(.*?)">(.*?)</a></td>').findall(rows[0])

	for href, alt in rows1:
	    
	    i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
	    u  = sys.argv[0] + '?mode=PLAY2'
	    u += '&url=%s'%urllib.quote_plus(href)
	    i.setProperty('IsPlayable', 'true')
	    xbmcplugin.addDirectoryItem(h, u, i, True)
        xbmcplugin.endOfDirectory(h)

def PLAY1(params):
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('url in Play', urllib.unquote_plus(params['url']))
	if http == None: return False
	rows1 = re.compile('<a  href="(.*?).avi"').findall(http)
#	showMessage('rows1', rows1)
#	r1 = rows1[0]
	if len(rows1) == 0:
		showMessage('УпС', 'Нет видеофайла')
		return False
	xbmc.Player().play(rows1[0]+'.avi')


def PLAY2(params):
	http = urllib.unquote_plus(params['url'])
	if http == None: return False
	xbmc.Player().play(http)


def OPEN_MOVIES1(params):
#	showMessage('url',urllib.unquote_plus(params['url']) )
	http = GET(urllib.unquote_plus(params['url']))
	
	if http == None: return False
	
	r1 = re.compile('<td id="menusel" colspan="2">(.*?)<!--LiveInternet counter-->',re.S).findall(http)
	r2 = re.compile('<a href="(.*?)" title="(.*?)"><img src="(.*?)" alt="(.*?)" width="60" height="90" border="1"></a>').findall(r1[0])
#	r3 = re.compile('<img src=(.*?) border',re.S).findall(r1[0])
	r3 = re.compile('title="(.*?)"><font color=').findall(r1[0])
	r4 = re.compile('</h2>\s*<font size="1">(.*?)</font><br>').findall(r1[0]) 
	
#	showMessage('img', r3)	
	
#	li = xbmcgui.ListItem("...", iconImage = icon, thumbnailImage = icon)
#	uri = sys.argv[0] + '?mode=ROOT'
#	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	rr=0

	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, name, img, alt in r2:

		
#		img = httpSiteUrl + img.replace('_60x90','_650x')
		img = httpSiteUrl + img.replace('_60x90','_160x235')
		rrr = r3[rr]
		rrr = rrr[:-5]
		rrr = rrr.replace('0', '☆☆☆☆☆')
		rrr = rrr.replace('1', '✬☆☆☆☆')
		rrr = rrr.replace('2', '★☆☆☆☆')
		rrr = rrr.replace('3', '★✬☆☆☆')
		rrr = rrr.replace('4', '★★☆☆☆')
		rrr = rrr.replace('5', '★★✬☆☆')
		rrr = rrr.replace('6', '★★★☆☆')
		rrr = rrr.replace('7', '★★★✬☆')
		rrr = rrr.replace('8', '★★★★☆')
		rrr = rrr.replace('9', '★★★★✬')
		rrr = '[COLOR ffFF4500]%s[/COLOR]' % (rrr)
		rr3 = '[COLOR ffDAA520]%s[/COLOR]' % r3[rr]
		alt = alt + '      ' + rrr + '  ' + rr3 + '   ' + r4[rr]
		i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
#		showMessage('img', img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
#		u += '&name=%s'%urllib.quote_plus(name)
#		u += '&img=%s'%urllib.quote_plus(img)
		rr=rr+1
		i.setProperty('IsPlayable', 'true')
		xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
		rp = re.compile('<tr><td>&nbsp;</td></tr>(.*?)</tr>\s*</table>\s*</td>', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)" class="page">(.*?)</a>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=OPEN_MOVIES'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass	
		
		
	xbmcplugin.endOfDirectory(h)


def OPEN_MOVIES(params):
#	showMessage('url',urllib.unquote_plus(params['url']) )
	http = GET(urllib.unquote_plus(params['url']))
	
	if http == None: return False
	
	r1 = re.compile('<td id="menusel">(.*?)<!--LiveInternet counter-->',re.S).findall(http)
	r2 = re.compile('<a href="(.*?)" title="(.*?)"><img src="(.*?)" alt="(.*?)" width="60" height="90" border="1"></a>').findall(r1[0])
#	r3 = re.compile('<img src=(.*?) border',re.S).findall(r1[0])
	r3 = re.compile('title="(.*?)"><font color=').findall(r1[0])
	r4 = re.compile('</h2>\s*<font size="1">(.*?)</font><br>').findall(r1[0]) 
	
#	showMessage('img', r3)	
	
	li = xbmcgui.ListItem("...", iconImage = icon, thumbnailImage = icon)
	uri = sys.argv[0] + '?mode=ROOT'
	xbmcplugin.addDirectoryItem(h, uri, li, True)
	
	rr=0

	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, name, img, alt in r2:

		
#		img = httpSiteUrl + img.replace('_60x90','_650x')
		img = httpSiteUrl + img.replace('_60x90','_160x235')
		rrr = r3[rr]
		rrr = rrr[:-5]
		rrr = rrr.replace('0', '☆☆☆☆☆')
		rrr = rrr.replace('1', '✬☆☆☆☆')
		rrr = rrr.replace('2', '★☆☆☆☆')
		rrr = rrr.replace('3', '★✬☆☆☆')
		rrr = rrr.replace('4', '★★☆☆☆')
		rrr = rrr.replace('5', '★★✬☆☆')
		rrr = rrr.replace('6', '★★★☆☆')
		rrr = rrr.replace('7', '★★★✬☆')
		rrr = rrr.replace('8', '★★★★☆')
		rrr = rrr.replace('9', '★★★★✬')
		rrr = '[COLOR ffFF4500]%s[/COLOR]' % (rrr)
		rr3 = '[COLOR ffDAA520]%s[/COLOR]' % r3[rr]
		alt = alt + '      ' + rrr + '  ' + rr3 + '   ' + r4[rr]
		i = xbmcgui.ListItem(alt, iconImage=img, thumbnailImage=img)
#		showMessage('img', img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
#		u += '&name=%s'%urllib.quote_plus(name)
#		u += '&img=%s'%urllib.quote_plus(img)
		rr=rr+1
		i.setProperty('IsPlayable', 'true')
		xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
		rp = re.compile('<tr><td>&nbsp;</td></tr>(.*?)</tr>\s*</table>\s*</td>', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)" class="page">(.*?)</a>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=OPEN_MOVIES'
			u += '&url=%s'%urllib.quote_plus(httpSiteUrl + href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass	
		
		
	xbmcplugin.endOfDirectory(h)

def get_params(paramstring):
	param=[]
	if len(paramstring)>=2:
		params=paramstring
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

params=get_params(sys.argv[2])


mode = None

try:
	mode = urllib.unquote_plus(params['mode'])
except:
	ROOT()

if mode == 'ROOT': ROOT()
if mode == 'OPEN_MOVIES': OPEN_MOVIES(params)
if mode == 'OPEN_MOVIES1': OPEN_MOVIES1(params)
if mode == 'PLAY1': PLAY1(params)
if mode == 'PLAY2': PLAY2(params)

